import { TOKENNAME, APP_LANG, BASE_URL, DEFAULT_LANG } from "@/config.js"
import { mapState, mapGetters } from 'vuex'
import { types } from '@/store/lang.js'
import dayjs from 'dayjs'
import permision from '@/utils/permission.js'
import { actionAction, actionDelAction } from '@/api/action.js'
export default {
	data() {
		return {
			defaultAvatar: require('@/static/image/common/nullAvatar.png'),
			backImg: require('@/static/image/common/back.png'),
			defaultColor: '#d2d2d3',
			likedColor: '#F94404'
		}
	},
	computed: {
		baseUrl() {
			return BASE_URL
		},
		// 用户基本信息
		userInfo() {
			return this.$store.state.common.userInfo
		},
		// 商家基本信息
		shopInfo() {
			return this.$store.state.common.shopInfo
		},
		// 系统软键盘高度
		keyboardHeight() {
			return this.$store.state.common.keyboardHeight
		},
		// 系统底部安全区域高度
		safeHeight() {
			let systemInfo = uni.getSystemInfoSync();
			return uni.upx2px(systemInfo.safeArea.top)
		},
		// 系统状态栏高度
		status_bar_height() {
			let systemInfo = uni.getSystemInfoSync();
			return systemInfo.statusBarHeight
		},
		// 设备高度
		deviceHeight() {
			let systemInfo = uni.getSystemInfoSync();
			return systemInfo.windowHeight
		},
		...mapGetters(types),
		// 余额、积分、购物车数、收藏、拼团
		userData() {
			return this.$store.state.user.userData || {}
		},
		// 获取余额
		balance() {
			return this.userData.banlance || 0
		},
		integral() {
			return this.userData.integral || 0
		},
		// 购物车数量
		cartCount() {
			return this.userData.cartCount || 0
		},
		
		// 定位状态
		locationStatus() {
			return this.$store.state.common.locationStatus || 0
		},
		locationLatlng() {
			return this.$store.state.common.locationLatlng || ''
		},
		
		shopcartAddress() {
			return this.$store.state.user.shopcartAddress || {}
		},
		
		hotWordList() {
			return this.$store.state.user.hotWordList || []
		},
		
		// 签到状态
		signStatus() {
			return this.$store.state.common.signStatus
		},
		// 消息体
		messageInfo() {
			return this.$store.state.common.messageInfo
		},
		// 客服电话
		contactPhone() {
			return this.$store.state.common.contactPhone || ''
		},
		// 是否第一次进入onShow
		isFirst() {
			return this.$store.state.common.isFirst
		},
		lang() {
			return uni.getStorageSync(APP_LANG) || DEFAULT_LANG
		}
	},
	methods: {
		dayjs,
		formatTime(dateStr = '') {
			return dayjs(dateStr || dayjs()).format('YYYY-MM-DD HH:mm')
		},
		formatAddress(obj = { country: '', province: '', city: '', area: '', address: '' }, sort = false) {
			let { country, province, city, area, address } = obj
			country = country || ''
			province = province || ''
			city = city || ''
			area = area || ''
			address = address || ''
			let result = sort ? (country + province + city + area + address) : (address + area + city + province + country)
			return result
		},
		// 是否开启APP位置信息  -1系统的定位没开启，0APP定位没开启，1全部开启
		async authLocation(status = false) {
			const { isIos, requestAndroidPermission, judgeIosPermission, checkSystemEnableLocation } = permision
			let { commit } = this.$store
			let systemLocation = await checkSystemEnableLocation(1)
			console.log(systemLocation)
			if (!systemLocation) {
				commit('UPDATE_LOCATION_STATUS', 0)
				return -1
			};
			let hasPermission = true
			if (status) {
				if (isIos) {
					hasPermission = await judgeIosPermission('location')
				} else {
					let androidSetting = await requestAndroidPermission('android.permission.ACCESS_FINE_LOCATION')
					hasPermission = androidSetting === 1
				}
			}
			commit('UPDATE_LOCATION_STATUS', hasPermission ? 1 : 0)
			return hasPermission
		},
		// 是否开启APP通讯录
		async authContact() {
			const { isIos, requestAndroidPermission, judgeIosPermission } = permision
			let status = true
			if (isIos) {
				status = await judgeIosPermission('contact')
			} else {
				let androidSetting = await requestAndroidPermission('android.permission.CALL_PHONE')
				status = androidSetting === 1
			}
			this.$store.commit('UPDATE_CONTACT_STATUS', status ? 1 : 0)
			return status
		},
		async authCamera() {
			const { isIos, requestAndroidPermission, judgeIosPermission } = permision
			let status = true
			if (isIos) {
				status = await judgeIosPermission('camera')
			} else {
				let androidSetting = await requestAndroidPermission('android.permission.CAMERA')
				status = androidSetting === 1
			}
			return status
		},
		// 处理图片
		dealImage(urls = '', split = ',') {
			let arr = urls && urls.split(split) || []
			return arr.map(item => {
				let [url, params] = item.split("?");
				let l = url.split(".");
				let type = l[l.length - 1].toLowerCase();
				let imageTypes = ["xbm", "tif", "pjp", "svgz", "jpg", "jpeg", "ico", "tiff", "gif", "svg", "jfif", "webp",
						"png", "bmp", "pjpeg", "avif"
					]
				let videoTypes = ["mp4", "swf", "avi", "flv", "mpg", "rm", "mov", "wav", "asf", "3gp", "mkv", "rmvb"]
				let isImage = imageTypes.includes(type);
				let isVideo = videoTypes.includes(type);
				let cover = (params && params.split("cover=")[1]) || "";
				return {
					type: isVideo ? 'video' : 'image',
					percent: 100,
					fileUrl: url,
					cover
				};
			})
		},
		// 显示图片
		showImage(url = '', url2 = '') {
			if (url2 === 'logo') {
				url2 = require('@/static/image/first/logo@2x.png')
			}
			return url && (this.baseUrl + url) || url2 || this.defaultAvatar
		},
		// 预览图片
		previewImage(urls, current = 0) {
			uni.previewImage({
				urls,
				current
			})
		},
		mockAction(count = 0, obj) {
			let list = []
			for (let i = 0; i < count; i++) {
				list.push({ id: i, status: parseInt(Math.random() * 2) })
			}
			return list
		},
		// type
		// 1是点赞笔记notesId，2是关注userId，3.收藏店铺merchantId
		// 4.收藏商品goodsId，5.拉黑userId，6.浏览用户userId
		// 7.浏览笔记notesId，8点赞评论commentId，9收藏笔记collectId
		actionAction(type = 1, item = {}) {
			let keys = ['', 'notesId', 'userId', 'merchantId', 'goodsId', 'userId', 'userId', 'notesId', 'commentId', 'notesId']
			let tipsKeys = ['', '点赞', '关注', '收藏店铺', '收藏商品', '拉黑', '', '', '点赞', '收藏笔记']
			return new Promise(resolve => {
				if (!item[keys[type]]) {
					resolve(0)
					return
				}
				let ActionKeys = ['', 'likeActionId', 'followActionId', 'collectActionId', 'collectActionId', 'collectActionId', 'collectActionId', 'collectActionId', 'likeActionId', 'collectActionId']
				let queryFn = fn => fn.then(() => {
						let isCancel = item[ActionKeys[type]]
						let tip = tipsKeys[type]
						if (tip) {
							this.$api.msg(`${ isCancel ? '取消' : '' }${ tip }成功`)
						}
						if ([3, 4, 9].includes(type)) {
							this.$store.dispatch('initUserData')
						}
						resolve(1)
					}).catch(e => {
						resolve(0)
					})
				queryFn(item[ActionKeys[type]] ? actionDelAction({ actionIds: item[ActionKeys[type]] }) : actionAction({ type, assignId: item[keys[type]] }))
			})
		},
		// 轮播图操作
		bannerClickAction(item) {
			// redirectType 0表示不跳转，1外链,2商家，3商品，4活动
			let { redirectType, redirectUrl, assignId } = item
			if (redirectType) {
				if (redirectType === 1) {
					// 打开自带浏览器失败时触发
					plus.runtime.openURL(encodeURI(redirectUrl), err => {
						this.jumpUrl(`/pages/other/webview/webview?url=${ encodeURIComponent(redirectUrl) }`)
					}, '')
				} else if (redirectType === 2) {
					this.jumpUrl(`/pages/user/comerciante/detail/detail?merchantId=${ assignId }`)
				} else if (redirectType === 3) {
					this.jumpUrl(`/pages/user/shop/detail/detail?goodsId=${ assignId }`)
				} else if (redirectType === 4) {
					this.jumpUrl(`/pages/user/personal/extension/detail/detail?activityId=${ assignId }`)
				}
			}
		},
		// 获取元素
		async query(name = '') {
			return new Promise(resolve => {
				uni.createSelectorQuery().in(this).select(name).boundingClientRect((res) => {
					resolve(res)
				}).exec()
			})
		},
		jumpUrl(url = '', needLogin = false) {
			console.log(url)
			if (url) {
				if (needLogin) {
					if (!uni.getStorageSync(TOKENNAME)) {
						return
					}
				}
				uni.navigateTo({ url })
			}
		},
		// 返回首页
		jumpIndex() {
			uni.switchTab({
				url: '/pages/tabbar/user/index/index'
			})
		},
		// 返回上一级
		jumpBack(delta = 1) {
			delta = typeof delta === 'number' ? delta : 1
			uni.navigateBack({ delta })
		},
		// 拨打电话
		async callAction(phoneStr = '') {
			let result = await this.authContact() 
			if (result) {
				uni.makePhoneCall({
					phoneNumber: phoneStr
				})
				return ''
			} else {
				return 'contact'
			}
		},
		// 复制内容
		copyContent(text = '') {
			uni.setClipboardData({
				data: text,
				showToast: false,
				success: e => {
					this.$api.msg('复制成功')
				}
			})
		},
		// 格式化点赞数量
		formatNumber(number = 0) {
			let units = ['k', 'm']
			if (number > 999999) {
				return (number / 1e6).toFixed(1) + 'm'
			} else if (number > 999) {
				return (number / 1e3).toFixed(1) + 'k'
			} else {
				return number
			}
		},
	}
}
